﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using Model;

namespace TaxiDispatchClient
{
    public partial class ServerConfigManagementForm : DevExpress.XtraEditors.XtraForm
    {
        public ServerConfigManagementForm()
        {
            InitializeComponent();
        }

        private void ServerConfigManagementForm_Load(object sender, EventArgs e)
        {
            _isLoad = true;
            Thread thread = new Thread(BindData);
            thread.Start();
        }

        private bool _isLoad;
        private string _oldName;

        private void BindData()
        {
            try
            {
                DataSet ds = MainForm.PositionService.ServerConfigGetList("");
                if(ds!=null&&ds.Tables.Count==1)
                {
                    BeginInvoke(new MethodInvoker(() =>
                        {
                            gridControl1.DataSource = ds.Tables[0];
                            gridView1.GroupPanelText = "现有" + ds.Tables[0].Rows.Count +
                                                        "个服务器";
                            gridView1_RowClick(null,null);
                        }));                    
                    if(_isLoad)
                    {
                        SetGvStyle();
                        _isLoad = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);                                
            }    
        }

        private void SetGvStyle()
        {
            BeginInvoke(new MethodInvoker(() =>
            {              
                gridView1.RowHeight = 22;
                gridView1.OptionsBehavior.Editable = false;
                gridView1.Columns["id"].Visible = false;
                gridView1.Columns["ServerName"].Caption = "服务器名称";
                gridView1.Columns["ServerName"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["ServerName"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["LongitudeOffset"].Caption = "经度偏移量";
                gridView1.Columns["LongitudeOffset"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["LongitudeOffset"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["LatitudeOffset"].Caption = "纬度偏移量";
                gridView1.Columns["LatitudeOffset"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["LatitudeOffset"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["DNSURL"].Caption = "DNS Url";
                gridView1.Columns["DNSURL"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
                gridView1.Columns["DNSURL"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;              
            }));

        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if(btn_add.Tag.ToString()=="新增")
            {                
                SetControlEnable(true,true);
                btn_add.Tag = "保存";
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
                textEdit_servername.Focus();
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Visible = false;
                btn_delete.Visible = false;
            }
            else
            {
                //验证输入值

                Thread thread = new Thread(AddNewConfig);
                thread.Start();                
            }
        }

        private void btn_modify_Click(object sender, EventArgs e)
        {
            if (btn_modify.Tag.ToString() == "修改")
            {                
                SetControlEnable(true);                
                btn_modify.Tag = "保存";
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
                textEdit_servername.Focus();
                btn_cancel.Visible = true;                
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Location = btn_add.Location;
                btn_add.Visible = false;
                btn_delete.Visible = false;

            }
            else
            {
                //验证输入值
                
                Thread thread = new Thread(ModiyfyConfig);
                thread.Start();
            }
        }

        private void ModiyfyConfig()
        {
            string name = textEdit_servername.Text;
            if(name !=_oldName)
            if (MainForm.PositionService.ServerConfigGetModelByName(name) != null)
            {
                XtraMessageBox.Show("该服务器名称已使用，请核对！");
                return;
            }
            string lng = textEdit_lng.Text;
            string lat = textEdit_lat.Text;
            string dnsurl = textEdit_dnsUrl.Text;
            ServerConfigInfo model = new ServerConfigInfo();
            model.id = int.Parse(label_id.Text);
            model.ServerName = name;
            model.LatitudeOffset =lat;
            model.LongitudeOffset = lng;
            model.DNSURL = dnsurl;
            if (MainForm.PositionService.ServerConfigUpdate(model))
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    SetControlEnable(false, true);
                    btn_modify.Tag = "修改";
                    btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                    btn_modify.Enabled = false;
                    
                    btn_cancel.Visible = false;
                    btn_modify.Location = btn_cancel.Location;
                    btn_add.Visible = true;
                    btn_delete.Visible = true;
                }));              
                XtraMessageBox.Show("服务器配置修改成功！");
                BindData();
            }
            else
            {
                XtraMessageBox.Show("服务器配置修改失败，请重试！");
            }
        }

        private void AddNewConfig()
        {
            string name = textEdit_servername.Text;
            if(MainForm.PositionService.ServerConfigGetModelByName(name)!=null)
            {
                XtraMessageBox.Show("该服务器名称已使用，请核对！");
                return;
            }                        
            string lng = textEdit_lng.Text;
            string lat = textEdit_lat.Text;
            string dnsurl = textEdit_dnsUrl.Text;
            ServerConfigInfo model = new ServerConfigInfo();
            model.ServerName = name;
            model.LatitudeOffset = lat;
            model.LongitudeOffset = lng;
            model.DNSURL = dnsurl;
            if (MainForm.PositionService.ServerConfigAdd(model))
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    SetControlEnable(false, true);
                    btn_add.Tag = "新增";
                    btn_add.Image = Properties.Resources.UserForm_btnadd001;
                    btn_cancel.Visible = false;
                    btn_modify.Visible = true;
                    btn_delete.Visible = true;
                }));                
                XtraMessageBox.Show("服务器配置添加成功！");             
                BindData();
            }
            else
            {
                XtraMessageBox.Show("服务器配置添加失败，请重试！");                
            }
        }


        private void SetControlEnable(bool isEnable,bool isClear = false)
        {
            textEdit_dnsUrl.Enabled = isEnable;
            textEdit_lat.Enabled = isEnable;
            textEdit_lng.Enabled = isEnable;
            textEdit_servername.Enabled = isEnable;
            if(isClear)
            {
                textEdit_dnsUrl.Text = "";
                textEdit_lat.Text = "";
                textEdit_lng.Text = "";
                textEdit_servername.Text = "";
                label_id.Text = "";
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if(row!=null)
            {
                textEdit_servername.Text = row["ServerName"].ToString();
                textEdit_lng.Text = row["LongitudeOffset"].ToString();
                textEdit_lat.Text = row["LatitudeOffset"].ToString();
                textEdit_dnsUrl.Text = row["DNSURL"].ToString();
                label_id.Text = row["id"].ToString();
                btn_modify.Enabled = true;
                btn_delete.Enabled = true;
                _oldName = row["ServerName"].ToString();
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            SetControlEnable(false,true);
            btn_add.Tag = "新增";
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            btn_modify.Enabled = false;
            btn_add.Visible = true;
            btn_modify.Visible = true;
            btn_delete.Visible = true;            
            btn_cancel.Visible = false;
            btn_modify.Location = btn_cancel.Location;
            gridView1_RowClick(null, null);
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            if(XtraMessageBox.Show("是否删除【"+textEdit_servername.Text+"】服务器",
                "提醒：",MessageBoxButtons.OKCancel)== DialogResult.OK)
            {
               Thread   thread = new Thread(DeleteConfig);
               thread.Start();
            }
        }
        
        private void DeleteConfig()
        {
            int id = int.Parse(label_id.Text);
            if (MainForm.PositionService.ServerConfigDelete(id))
            {
                XtraMessageBox.Show("删除成功！");
            }
            else
            {
                XtraMessageBox.Show("删除失败！");
            }
            BindData();
        }

        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion
    }
}